import { CSSProperties, FC, memo, useEffect, useRef, useState } from "react";
import { ComponentProps } from "../types/common";
import { IProps } from "../types/echartsMap";
import * as echarts from "echarts";
import { debounce } from "lodash";

const EchartsMap: FC<ComponentProps<false, IProps>> = memo((props) => {
  const [styles] = useState<CSSProperties>({
    width: props.width || '100%',
    height: props.height || '100%'
  }),
  echartWrapper = useRef<HTMLDivElement | null>(null),
  echartsIns = useRef<echarts.ECharts | null>(null)

  // 初始化 echarts
  const initEcharts = () => {
    echartsIns.current = echarts.init(echartWrapper.current, props.theme || 'light')
    echarts.registerMap(props.mapId, props.mapData)
    echartsIns.current.setOption(props.options)

    // 注册事件
    echartsIns.current.on('click', (...args) => {
      props.handleClick?.(...args)
    })

    echartsIns.current.on('mouseover', (...args) => {
      props.handleMouseOver?.(...args)
    })
  }

  // 变化
  const setResize = debounce(() => echartsIns.current?.resize(), props.resizeDelay || 500)

  // 清理函数
  const clearEffect = () => {
    window.removeEventListener('resize', setResize, false)
  }

  
  // 配置发生变化
  useEffect(() => {
    echartsIns.current?.setOption(props.options)
  }, [props.options])

  useEffect(() => {
    initEcharts()
    setResize()
    window.addEventListener('resize', setResize, false)

    return clearEffect
  }, [])

  return (
    <div ref={echartWrapper} style={{ ...styles }}></div>
  )
})

export default EchartsMap